package com.erp.erp_ui.BillExchangeInfo;

import com.erp.enums.ModuleTypeEnum;
import com.erp.erp_entitys.bill_declare.InfoSearch;
import com.erp.erp_entitys.bill_declare.carryInfoSearch;
import com.erp.erp_entitys.bill_declare.statSearch;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_entitys.warehouse.entity.TempAnnexEntity;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.warehouse.IAnnexService;
import com.erp.erp_servers.warehouse.ITempAnnexService;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.req.AnnexReq;
import com.erp.erp_ui.warehouse.vo.AnnexVo;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.utils.UploadFile;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

public class ChangeUnit {
    public static InfoSearch getSearch(InfoSearch search){
        if(search.getBill()!=null&&search.getBill().equals("")){
            search.setBill(null);
        }
        if(search.getBoxStatus()!=null&&search.getBoxStatus().equals("")){
            search.setBoxStatus(null);
        }
        if(search.getCarryEnd()!=null&&search.getCarryEnd().equals("")){
            search.setCarryEnd(null);
        }
        if(search.getCarryStar()!=null&&search.getCarryStar().equals("")){
            search.setCarryStar(null);
        }
        if(search.getCompany_code()!=null&&search.getCompany_code().equals("")){
            search.setCompany_code(null);
        }
        if(search.getInvoiceEnd()!=null&&search.getInvoiceEnd().equals("")){
            search.setInvoiceEnd(null);
        }
        if(search.getInvoiceStar()!=null&&search.getInvoiceStar().equals("")){
            search.setInvoiceStar(null);
        }
        if(search.getOp_code()!=null&&search.getOp_code().equals("")){
            search.setOp_code(null);
        }
        if(search.getSalesman_code ()!=null&&search.getSalesman_code().equals("")){
            search.setSalesman_code(null);
        }
        if(search.getSalesmanCode()!=null&&search.getSalesmanCode().size()==0){
            search.setSalesmanCode(null);
        }
        if(search.getOperationCode()!=null&&search.getOperationCode().size()==0){
            search.setOperationCode(null);
        }
        return search;
    }
    public static statSearch getSearch(statSearch search){
        if(search.getBill()!=null&&search.getBill().equals("")){
            search.setBill(null);
        }
        if(search.getBoxStatus()!=null&&search.getBoxStatus().equals("")){
            search.setBoxStatus(null);
        }
        if(search.getCarryEnd()!=null&&search.getCarryEnd().equals("")){
            search.setCarryEnd(null);
        }
        if(search.getCarryStar()!=null&&search.getCarryStar().equals("")){
            search.setCarryStar(null);
        }
        if(search.getAtdEnd()!=null&&search.getAtdEnd().equals("")){
            search.setAtdEnd(null);
        }
        if(search.getAtdStar()!=null&&search.getAtdStar().equals("")){
            search.setAtdStar(null);
        }

        if(search.getStockStar()!=null&&search.getStockStar().equals("")){
            search.setStockStar(null);
        }
        if(search.getStockEnd()!=null&&search.getStockEnd().equals("")){
            search.setStockEnd(null);
        }
        if(search.getEtdStar()!=null&&search.getEtdStar().equals("")){
            search.setEtdStar(null);
        }
        if(search.getEtdEnd()!=null&&search.getEtdEnd().equals("")){
            search.setEtdEnd(null);
        }
        if(search.getEtaStar()!=null&&search.getEtaStar().equals("")){
            search.setEtaStar(null);
        }
        if(search.getEtaEnd()!=null&&search.getEtaEnd().equals("")){
            search.setEtaEnd(null);
        }
        if(search.getCompany_code()!=null&&search.getCompany_code().equals("")){
            search.setCompany_code(null);
        }
        if(search.getInvoiceEnd()!=null&&search.getInvoiceEnd().equals("")){
            search.setInvoiceEnd(null);
        }
        if(search.getInvoiceStar()!=null&&search.getInvoiceStar().equals("")){
            search.setInvoiceStar(null);
        }
        if(search.getOp_code()!=null&&search.getOp_code().equals("")){
            search.setOp_code(null);
        }
        if(search.getSalesman_code ()!=null&&search.getSalesman_code().equals("")){
            search.setSalesman_code(null);
        }
        if(search.getSalesmanCode()!=null&&search.getSalesmanCode().size()==0){
            search.setSalesmanCode(null);
        }
        if(search.getOperationCode()!=null&&search.getOperationCode().size()==0){
            search.setOperationCode(null);
        }

        return search;
    }
    public static carryInfoSearch getSearch(carryInfoSearch search){
        if(search.getContractno()!=null&&search.getContractno().equals("")){
            search.setContractno(null);
        }
        if(search.getCustomercontractno()!=null&&search.getCustomercontractno().equals("")){
            search.setCustomercontractno(null);
        }
        if(search.getCustomername()!=null&&search.getCustomername().equals("")){
            search.setCustomername(null);
        }
        if(search.getEndmdate()!=null&&search.getEndmdate().equals("")){
            search.setEndmdate(null);
        }
        if(search.getInvoiceno()!=null&&search.getInvoiceno().equals("")){
            search.setInvoiceno(null);
        }
        if(search.getMdate()!=null&&search.getMdate().equals("")){
            search.setMdate(null);
        }
        if(search.getNumberremaining()!=null&&search.getNumberremaining().equals("")){
            search.setNumberremaining(null);
        }
        return search;
    }
    public static List<AnnexVo> transferFileUpload(ITempAnnexService tempAnnexService, IFtpService ftpService, MultipartHttpServletRequest request, String ftpPath, String operator, String operatorNo) throws IOException {
        String fileType = "warehouse" + "/" + "transfer";
        List<UploadFile> fileList = ftpService.upload(request, fileType, ftpPath);

        List<AnnexVo> annexVos = new ArrayList<>();
        for(UploadFile uploadFile : fileList){
            //初始化回参对象
            AnnexVo annexVo = new AnnexVo();
            if(uploadFile.isStatus()){
                //上传成功,则添加记录到数据库
                TempAnnexEntity tempAnnex = new TempAnnexEntity();
                //设置模块id
                tempAnnex.setModuleId(ModuleTypeEnum.BILLCHANGE_FILE.getId());
                //设置文件名称
                tempAnnex.setFileName(uploadFile.getOriginalFileName());
                //设置文件路径
                tempAnnex.setFilePath(uploadFile.getFtpPath() + "/" + uploadFile.getFileName());
                //设置上传建时间
                tempAnnex.setUploadTime(new Date());
                //设置修改时间
                tempAnnex.setUpdateTime(new Date());
                //设置操作人
                tempAnnex.setOperator(operator);
                //设置操作人编码
                tempAnnex.setOperatorNo(operatorNo);
                //设置附件有效
                tempAnnex.setValid(1);

                //调用接口新增附件
                int res = tempAnnexService.insert(tempAnnex);
                //如果新增成功,则返回新增的附件对象
                if(1 == res){
                    //对象赋值
                    BeanUtils.copyProperties(tempAnnex, annexVo);
                    //日期转换
                    annexVo.setUploadTime(DateUtils.format(tempAnnex.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                    //设置上传状态
                    annexVo.setStatus(true);
                }else{
                    //新增失败,重新上传
                    //设置上传状态
                    annexVo.setStatus(false);
                }
            }else{
                //设置上传状态
                annexVo.setStatus(false);

            }
            //将返回对象实体放入集合中
            annexVos.add(annexVo);
        }
        return annexVos;
    }

    /**
     * 新增、修改
     * @param req 新增、修改入参
     * @param creator 创建人
     * @param createNo 创建人编码
     * @return 新增、修改结果
     */
    public static R add(ITempAnnexService tempAnnexService, IAnnexService annexService, List<AnnexReq> req, String creator, Integer id, String createNo) throws ParseException {

        //五：添加附件信息
        boolean flag = addAnnex(annexService,req, id, creator, createNo);
        if(!flag){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(tempAnnexService,req);
        return R.build(ResultStatusEnum.SUCCESS);
    }
    /**
     * 附件新增
     * @param annexReqs 附件信息
     * @param id 主表id
     * @param operator 操作人
     * @param operatorNo 操作人编码
     * @return 是否新增成功(true:成功 false:失败 )
     */
    private static boolean addAnnex(IAnnexService annexService,List<AnnexReq> annexReqs, Integer id, String operator, String operatorNo) {
        try {
            //没有附件,将该id关联的所有附件设为无效
            if(CollectionUtils.isEmpty(annexReqs)){
                AnnexEntity annexReq = new AnnexEntity();
                annexReq.setParentId(id);
                annexReq.setModuleId(ModuleTypeEnum.BILLCHANGE_FILE.getId());
                List<AnnexEntity> annexList = annexService.queryAll(annexReq);
                if(!CollectionUtils.isEmpty(annexList)){
                    for(AnnexEntity annex : annexList){
                        AnnexEntity updateAnnex= new AnnexEntity();
                        updateAnnex.setId(annex.getId());
                        //将被删除的附件设为失效
                        updateAnnex.setValid(DataIsValidEnum.INVALID.getId());
                        annexService.update(updateAnnex);
                    }
                }
                return true;
            }
            //存在附件,新增附件信息
            List<AnnexEntity> list = new ArrayList<>();
            //获取旧的附件id集合
            List<Integer> oldIds = new ArrayList<>();
            for(AnnexReq annexReq : annexReqs){
                if(null != annexReq.getNews()){
                    //属于旧附件 只取id,不新增
                    oldIds.add(annexReq.getId());
                    continue;
                }
                AnnexEntity annex = new AnnexEntity();
                BeanUtils.copyProperties(annexReq, annex);
                //设置关联模块id
                annex.setModuleId(ModuleTypeEnum.BILLCHANGE_FILE.getId());
                //设置关联模块父id
                annex.setParentId(id);
                //设置上传时间
                annex.setUploadTime(DateUtils.convertStringToDate(annexReq.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置修改时间
                annex.setUpdateTime(new Date());
                //设置操作人
                annex.setOperator(operator);
                //设置操作人编码
                annex.setOperatorNo(operatorNo);
                //设置数据有效
                annex.setValid(1);

                list.add(annex);
            }
            if(oldIds.size() > 0){
                //通过调拨id获取修改附件信息
                AnnexEntity annex = new AnnexEntity();
                annex.setModuleId(ModuleTypeEnum.BILLCHANGE_FILE.getId());
                annex.setParentId(id);
                //获取上次附件信息
                List<AnnexEntity> annexList = annexService.queryAll(annex);
                if(!CollectionUtils.isEmpty(annexList)){
                    //获取上次附件id集合
                    List<Integer> oldAnnexIds = annexList.stream().map(p -> p.getId()).collect(Collectors.toList());
                    //得到被删除的附件id
                    Collection collection = new ArrayList(oldAnnexIds);
                    collection.removeAll(oldIds);
                    if(collection.size() > 0){
                        Iterator<Integer> it = collection.iterator();
                        while (it.hasNext()){
                            int detailId = it.next();
                            AnnexEntity annexEntity = new AnnexEntity();
                            annexEntity.setId(detailId);
                            //将被删除的附件设为失效
                            annexEntity.setValid(DataIsValidEnum.INVALID.getId());

                            annexService.update(annexEntity);
                        }
                    }
                }
            }
            if(!CollectionUtils.isEmpty(list)){
                //附件批量新增
                int res = annexService.batchInsert(list);
                if(res == list.size()){
                    return true;
                }
            }
            return true;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }

    /**
     * 批量处理临时附件信息，将临时附件设置为失效
     * @param annexReqs
     */
    private static void deleteTempAnnex( ITempAnnexService tempAnnexService,List<AnnexReq> annexReqs){
        //没有附件
        if(CollectionUtils.isEmpty(annexReqs)){
            return;
        }
        //存在附件
        for(AnnexReq annex : annexReqs){
            if(null != annex.getNews()){
                //旧附件,不用修改
                continue;
            }
            TempAnnexEntity tempAnnex = new TempAnnexEntity();
            //设置临时附件id
            tempAnnex.setId(annex.getId());
            //设置修改时间
            tempAnnex.setUpdateTime(new Date());
            //将附件设置为失效
            tempAnnex.setValid(DataIsValidEnum.INVALID.getId());
            tempAnnexService.update(tempAnnex);
        }

    }
}
